﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using UnityEngine;

/// <summary>
/// 被ModelLocator引用
/// </summary>
public class Scene : ObjectData
{
	private RoleVo _role = new RoleVo (new Point ());
	private ScenePlayerLogic scenePlayerLogic;

	//private uint _propCount			=	0;
	/**
		 *表格表数据 
		 */		
	//public BaseObject _recTable	= 	new	BaseObject();

	private uint _recCount = 0;

	public Scene (uint modelId)
            : base(null, modelId.ToString())
	{
        //scenePlayerLogic = Camera.mainCamera.GetComponent<ScenePlayerLogic> ();//取得绑定对象的组件//
	}

	public void AddMainRole (Point objID, string playerName, string modelPath, string headPic, int profession)
	{
		string filePath = ResPath.PREFABPATH + "Player";
		GameObject mainRole = (GameObject)MonoBehaviour.Instantiate (Resources.Load (filePath));

		Camera camera = Camera.main;

		mainRole.transform.parent = camera.transform;
		mainRole.transform.localPosition = new Vector3 (-300, -210, 0);
		mainRole.transform.localScale = Vector3.one;
		mainRole.name = "mainRole";
		mainRole.tag = "SceneObject";

		UILabel nameLabel = mainRole.GetComponentInChildren<UILabel> ();
		nameLabel.text = playerName;

		ClipAnimation clipAni = mainRole.GetComponentInChildren<ClipAnimation> ();
		clipAni.filePath = modelPath;

		PlayerData.Instance ().MainRoleInstance = mainRole;

		PlayerAction pa = mainRole.GetComponent<PlayerAction> ();
		//Speed
		pa.speed = 1.1f;

		Role.Type = 1;
		Role.ModelId = 1;
		Role.HandlePropertiesEx ("RoleName", playerName);
		Role.HandlePropertiesEx ("HeadPic", headPic);
		Role.HandlePropertiesEx ("RoleID", profession);
		Role.HandlePropertiesEx ("ModelName", modelPath);

		string[] roleInfo = SqliteReader.getInstance ().getIniVal ("TeplatesInfo", "OType", Role.Type.ToString (), new string[] { "Struct", "Config", "Key" });

		InitXML.getInstance ().AnalyzeXml (roleInfo [0], roleInfo [1], roleInfo [2], profession.ToString (), Role);//主角人物的本地初始化//

			
		ByteArrayEx byteArray = new ByteArrayEx ();
		
		byteArray.writeInt ((int)SystemMsgFlag.NetMessageCS.NM_CS_ROLE_CREATE_SUCCESS_SYN);
			
		MySocket.getInstance ().Async_Send (byteArray.byteArray);
	}


	/// <summary>
	/// 场景增加主角对象
	/// </summary>
	/// <param name="objID">对象唯一ID</param>
	/// <param name="type">对象类型</param>
	/// <param name="modelId">对象modeID</param>
	/// <param name="count">对象数</param>
	/// <param name="msg"></param>
	public void AddObj (Point objID, int type, int modelId, int count, ByteArrayEx msg)
	{
		//if (type == ObjType.Player)
		//{
		//    if (objID.equals(Role.ObjID))
		//    {
		Role.Type = type;
		Role.ModelId = modelId;

		string[] roleInfo = SqliteReader.getInstance ().getIniVal ("Base", "OType", ObjType.Player.ToString (), new string[] { "Struct" });
		InitXML.getInstance ().AnalyzeXml (roleInfo [0], Role);//主角人物的本地初始化//
                    
		Role.setPropertiesFormByteArrayEx (count, msg);
                    
		//    }
		//}
	}

	public void RemoveObj (Point objID)
	{
		SceneObject tobj = GetObject (objID);
		if (tobj != null) {
			DeletePropertiesEx (objID.x + "." + objID.y);
		} else {
			Console.WriteLine ("移除对象失败" + objID.x + "," + objID.y);
		}
	}

	/**
		 * 根据Point获取对象实例
		 * @return 返回对象实例
		 * 
		 */				
	public SceneObject GetObject (Point objID)
	{
		if (!CheckProperties (objID.ToString ())) {
			return null;
		}
		return GetProperties (objID.ToString ()) as SceneObject;
	}

	/**
		 *	不通过回调直接取属性 
		 * @param val 属性名
		 * @return 属性值
		 * 
		 */		
	public object GePropertyEx (string val)
	{
		return	GetProperties (val);
	}

	/*
        public Record GetRecordEx(string val)
        {
            return GetProperties(val) as Record;
        }
         * */
        

	public View GetView (int viewid)
	{
		//视图名临时这么写
		string viewName = "View" + viewid.ToString ();
			
		if (CheckProperties (viewName)) {
			return (View)GetProperties (viewName);	
		}						
		return null;
	}

	public void Clear ()
	{			
		//super.clearProperties();
		//清除掉场景对象,视图,表格,其他不能清
		getDataForEach (eachfunc);
	}

	private void eachfunc (string propName, object val)
	{
		if (val is SceneObject && !(val is RoleVo)) {//主角信息不删除//
			DeletePropertiesEx (propName);
		}
	}

	public void SetRecordTable (ByteArrayEx msg, uint count)
	{
		_recCount = count;
		// string		strName;	// 表格名称，以0结束的字符串，前面不包含长度
		// _UI16		nCols;		// 列数，最大256
		// _UI08		nColType[];	// 列类型
		// ... 其他表的信息
			
		for (int i = 0; i < count; i++) {
			string recName = msg.readMultiByteEx ();
			uint nCols = msg.readUnsignedShort ();
			List<int> nColType = new List<int> ();
				
			for (int j = 0; j < nCols; j++) {
				nColType [j] = msg.readByte ();
			}
				
			//_recTable.HandleProperties(i.ToString(),recName);			
				
			//以表名为索引存放表格对象
			Record record = new Record (recName);
			record.SetColType (nColType);				
			HandlePropertiesEx (recName, record);
				
			Console.WriteLine (i + "," + recName + "," + nCols + "," + nColType);
		}
	}

	/*
        public string GetRecordName(uint index)
		{
			return (string)_recTable.GetProperties(index.ToString());
		}
        **/

    ////添加obj
    //public void AddObjByCustom (Point objID)
    //{
    //    scenePlayerLogic.addNpc (objID);
    //}

	public void AddObjByCustom (params object[] pList)
	{
		//要添加的obj个数
		int objCount = (int)pList [0];
		//单个obj属性个数
		int pCount;
			
		SceneObject pObj;
		Point objId;
		//指针
		int index = 1;
			
		for (int i = 0; i < objCount; i++) {//对象循环
			pCount = ((int)pList [index++] - 1) << 1;
				
			objId = (Point)pList [index++];

			if (isRole (objId)) {//过滤自己
				index += pCount;
				continue;
			}
				
			//合并已经产生过的obj
			if (CheckProperties (objId.x + "." + objId.y)) {
				//假对象已经在了
				pObj = (SceneObject)GetProperties (objId.x + "." + objId.y);
			} else {
				scenePlayerLogic.addPlayer(objId);
				//GameObject createObj = scenePlayerLogic.getScenePlayerByID(objId);
				pObj = new SceneObject (objId, 0, 0);
				//pObj = createObj.AddComponent("SceneObject") as SceneObject;
			}

			for (int j = 0; j < pCount; j += 2) {//属性索引，属性值
				pObj.HandlePropertiesEx (pList [index + j].ToString (), pList [index + j + 1]);
			}
				
			HandlePropertiesEx (pObj.ObjKey, pObj);
				
			index += pCount;
                
		}
	}

	//根据objId删除obj
	public void DelObjByCustom (Point objID)
	{
		if (CheckProperties (objID.ToString ())) {
			scenePlayerLogic.removeNpc (objID);

			DeletePropertiesEx (objID.ToString ());
		}
	}

	//更新obj属性
	public void UpdataObjByCustom (params object[] pList)
	{
		SceneObject obj;//	=	GetProperties(objKey);
		string pName;
		Point p = (Point)pList [0];
		if (isRole (p)) {//过滤自己
			return;
		}

		string objKey = p.ToString ();
			
		if (CheckProperties (objKey)) {//是否有老的数据
			obj = (SceneObject)GetProperties (objKey);
			pName = (string)pList [1].ToString ();
			obj.HandlePropertiesEx (pName, pList [2]);

			//scenePlayerLogic.updataSceneObjByProperty(obj,pName);//不通过显示直接数据层修改（前提绑定）//
		}
	}

	public Boolean isRole (Point objId)
	{
		return _role.ObjID.equals (objId);
	}

	public RoleVo Role {
		get { return _role; }
	}

}
